﻿<template>

    <div>

        <el-dialog title="风险因素信息" v-loading="isLoading" :visible.sync="itemDlgVisible" :close-on-click-modal="false">
            <el-form :model="sensAnalysisItem">
                <el-form-item label="编码" :label-width="formLabelWidth">
                    <el-input v-model="sensAnalysisItem.code" autocomplete="off" :disabled="editItemMode"></el-input>
                </el-form-item>
                <el-form-item label="名称" :label-width="formLabelWidth">
                    <el-input v-model="sensAnalysisItem.name" autocomplete="off" :disabled="editItemMode"></el-input>
                </el-form-item>

                <el-form-item label="录入指标"
                              :label-width="formLabelWidth">
                              <el-cascader :props="recordFieldCascaderProps"
                                           :options="inputTableList"
                                           filterable
                                           v-model="sensAnalysisItem.fieldIdList" :disabled="!modelEditable"></el-cascader>
<!--                    <el-cascader :props="{emitPath: false}"-->
<!--                                 :options="normalUnitList"-->
<!--                                 filterable-->
<!--                                 v-model="sensAnalysisItem.unitRef" :disabled="!modelEditable"></el-cascader>-->
                </el-form-item>
                <el-form-item label="评价值"
                              :label-width="formLabelWidth">
                    <el-cascader v-if="riskAnalysisConfig.balanceAnalysis" :props="{emitPath: false}"
                                 :options="computeUnitList"
                                 filterable
                                 v-model="sensAnalysisItem.baseValueRef" :disabled="!modelEditable"></el-cascader>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="itemDlgVisible = false">取 消</el-button>
                <el-button v-if="editItemMode&&modelEditable" type="primary" @click="updateItem">修 改</el-button>
                <el-button v-else-if="modelEditable" type="primary" @click="createItem">创 建</el-button>
            </div>
        </el-dialog>
        <el-dialog title="主要指标配置" v-loading="isLoading" :visible.sync="configDlgVisible" width="600px" :close-on-click-modal="false">
            <el-form :model="riskAnalysisConfig">
                <!--        <el-form-item label="标签页名称" :label-width="formLabelWidth">-->
                <!--          <el-input v-model="riskAnalysisConfig.sheetName" autocomplete="off" :disabled="!modelEditable"></el-input>-->
                <!--        </el-form-item>-->

                <el-form-item label="敏感性分析指标"
                              :label-width="formLabelWidth">
                    <el-cascader :props="{emitPath: false,multiple:true}"
                                 :options="computeUnitList"
                                 filterable
                                 v-model="riskAnalysisConfig.computeUnitRefList"
                                 :disabled="!modelEditable"></el-cascader>
                </el-form-item>
                <el-form-item label="敏感性因素"
                              :label-width="formLabelWidth">
                    <data-select multiple="true"
                                 :data="itemList"
                                 v-model="riskAnalysisConfig.sensAnalysisItemList"
                                 :disabled="!modelEditable"></data-select>
                </el-form-item>
                <el-form-item label="敏感因素变化(%)"
                              :label-width="formLabelWidth">
                    <el-col :span="11">
                        <el-input-number v-model="riskAnalysisConfig.changeStep" :min="2.5" :max="10"
                                         @change="changeStep" :step="2.5" step-strictly>
                            <template slot="append">%</template>
                        </el-input-number>
                    </el-col>

                </el-form-item>
                <el-form-item label="" :label-width="formLabelWidth">
                    <el-alert style="line-height:normal"
                              :title="showChangeRate(riskAnalysisConfig)"
                              type="success"
                              :closable="false">
                    </el-alert>
                </el-form-item>
                <el-form-item label="保留小数位" :label-width="formLabelWidth">
                    <el-input v-model="riskAnalysisConfig.digit" type="number"></el-input>
                </el-form-item>
                <el-form-item label="展示图标" :label-width="formLabelWidth">
            <span style="padding: 10px;font-size:18px!important;text-align: center;height: auto;line-height: normal;">
              <i v-if="riskAnalysisConfig.icon" :class="riskAnalysisConfig.icon"></i>
              <i v-else>无</i>
            </span>
                    <el-popover
                            placement="right"
                            width="400"
                            v-model="showSelectIconProp"
                            trigger="manual">
                        <el-col span="4" v-for="icon in iconList"
                                style="font-size:18px!important;text-align:center;padding: 10px;height: auto;line-height: normal;"
                                :class="riskAnalysisConfig.icon==icon?'el-menu-item is-active':'el-menu-item'"
                                @click.native="riskAnalysisConfig.icon=icon,showSheetIcon=false">
                            <i :class="icon"></i>
                        </el-col>
                        <el-button slot="reference" type="primary" size="small" @click="showSheetIcon=true">更改
                        </el-button>
                    </el-popover>
                </el-form-item>
                <el-form-item label="基准收益率" :label-width="formLabelWidth">
                    <el-cascader :props="{emitPath: false}"
                                 :options="irrOptionList"
                                 filterable
                                 v-model="riskAnalysisConfig.baseIrrRef" :disabled="!modelEditable"></el-cascader>
                </el-form-item>
                <el-form-item label="内部收益率"
                              :label-width="formLabelWidth">
                    <el-cascader :props="{emitPath: false}"
                                 :options="computeUnitList"
                                 filterable
                                 v-model="riskAnalysisConfig.irrRef" :disabled="!modelEditable"></el-cascader>
                </el-form-item>
                <el-form-item label="净现值"
                              :label-width="formLabelWidth">
                    <el-cascader :props="{emitPath: false}"
                                 :options="computeUnitList"
                                 filterable
                                 v-model="riskAnalysisConfig.npvRef" :disabled="!modelEditable"></el-cascader>
                </el-form-item>
                <el-form-item label="投资回收期"
                              :label-width="formLabelWidth">
                    <el-cascader :props="{emitPath: false}"
                                 :options="computeUnitList"
                                 filterable
                                 v-model="riskAnalysisConfig.pbpRef" :disabled="!modelEditable"></el-cascader>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth">
                    <el-checkbox  :disabled="!modelEditable" v-model="riskAnalysisConfig.balanceAnalysis">基准/盈亏平衡性分析</el-checkbox>
                </el-form-item>
                <template v-if="riskAnalysisConfig.balanceAnalysis">

                    <el-form-item label="净利润"
                                  :label-width="formLabelWidth">
                        <el-cascader :props="{emitPath: false}"
                                     :options="computeUnitList"
                                     filterable
                                     v-model="riskAnalysisConfig.netProfitsRef"
                                     :disabled="!modelEditable"></el-cascader>
                    </el-form-item>
                </template>
                <el-form-item label="油价录入指标"
                              :label-width="formLabelWidth">
                    <el-cascader :props="singleRecordFieldCascaderProps"
                                 :options="inputTableList"
                                 filterable
                                 v-model="riskAnalysisConfig.oilPriceField"
                                 :disabled="!modelEditable"></el-cascader>
                </el-form-item>

<!--              <el-form-item label="现金流量"-->
<!--                            :label-width="formLabelWidth">-->
<!--                <el-cascader :props="{emitPath: false}"-->
<!--                             :options="normalUnitList"-->
<!--                             filterable-->
<!--                             v-model="riskAnalysisConfig.cashFlowRef" :disabled="!modelEditable"></el-cascader>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="成本因素"-->
<!--                            :label-width="formLabelWidth">-->
<!--                <data-select v-model="riskAnalysisConfig.costAnalysisItemId" :data="itemList"></data-select>-->
<!--              </el-form-item>-->
            </el-form>


            <div slot="footer" class="dialog-footer">
                <el-button @click="configDlgVisible = false">取 消</el-button>
                <el-button v-if="modelEditable" type="primary" @click="updateConfig">保 存</el-button>
            </div>
        </el-dialog>

        <el-table :data="itemList" border highlight-current-row empty-text="暂无数据"
                  :key="'sensAnalysis'+modelInfo.id" v-loading="loadingItem"
                  :header-cell-style="{background:'#f5f7fa'}">

            <el-table-column type="index" label="序号" align="center" width="50">
            </el-table-column>
          <el-table-column prop="code" label="编码" width="100" header-align="center" show-overflow-tooltip></el-table-column>

          <el-table-column prop="name" label="名称" width="100" header-align="center" show-overflow-tooltip>
            </el-table-column>
                  <el-table-column label="录入指标" header-align="center">
                    <template slot-scope="scope">
                      <el-tag v-for="field in scope.row.fieldList" :key="field.id">{{field.name}}</el-tag>
                    </template>
                  </el-table-column>
<!--            <el-table-column label="计算单元" header-align="center">-->
<!--                <template slot-scope="scope">-->
<!--                    <el-tag>{{scope.row.unit?scope.row.unit.name+'('+scope.row.unit.ref+')':''}}</el-tag>-->
<!--                </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="createDate" label="创建日期" width="180" align="center">-->
            <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            </el-table-column>

            <el-table-column
                    align="right" width="180">
                <template slot="header">
                    <el-button
                            v-if="modelEditable"
                            type="primary"
                            size="small"
                            @click="openCreateItemDlg">添加
                    </el-button>
                    <el-button
                            type="primary"
                            size="small"
                            @click="configDlgVisible=true">配置
                    </el-button>
                </template>
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            @click="openEditComputUnitDlg(scope.row)">
                        {{modelEditable?'编辑':'查看'}}
                    </el-button>
                    <el-button
                            v-if="modelEditable"
                            size="mini"
                            type="danger"
                            @click="deleteItem(scope.row.id)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

</template>

<script>
    import DataSelect from "../../components/data-select";
    export default {
        name: "RiskAnalysisModule",
      components: {DataSelect},
      $$route: {
            path: 'risk-analysis-module',
            parentName: 'ModelInfo',
        },
        props:{
            modelInfo:{}
        },
        data() {
            return {

                isLoading: false,
              loadingItem:false,
                formLabelWidth: '120px',
                sensAnalysisItem: {fieldIdList: []},
                itemList: [],
                itemDlgVisible: false,
                editItemMode: false,
                inputTableList: [],
                modelEditable: false,
                recordFieldCascaderProps: {
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    children: 'fieldList',
                    multiple: true,
                },
                singleRecordFieldCascaderProps: {
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    children: 'fieldList',
                    multiple: false,
                },
                configDlgVisible: false,
                normalUnitList: [],
                irrOptionList: [],
                computeUnitList: [],
                riskAnalysisConfig: {changeStep: 10, computeUnitRefList: []},
                showSheetIcon: false,
            }
        },
        computed: {
            showSelectIconProp: function () {
                if (this.configDlgVisible == false) {
                    this.showSheetIcon = false;
                }
                return this.configDlgVisible && this.showSheetIcon;
            }
        },
        created: function () {
            // const modelId = this.$route.params.id;
            const modelId = this.modelInfo.id;
            this.loadItemList(modelId);
            // this.loadModelInfo(modelId);
            this.modelEditable = this.modelInfo.state != 'publish';
            this.loadInputTableList(this.modelInfo.id);
            this.loadComputeUnitList(modelId);
            this.loadConfig(modelId);
        },
        methods: {
            // loadModelInfo: function (modelId) {
            //     this.$get("/model/" + modelId, {}, (response) => {
            //         this.modelInfo = response.data;
            //         this.modelEditable = this.modelInfo.state == 0;
            //         this.loadInputTableList(this.modelInfo.id);
            //     });
            // },
            loadInputTableList: function (modelId) {
                // this.isLoading = true;
                this.$get("/table/fulldata?modelId=" + modelId, {}, (response) => {
                    this.inputTableList = response.data;
                }, () => {
                    // this.isLoading = false;
                });
            },

            openCreateItemDlg: function () {
                this.itemDlgVisible = true;
                if (this.editItemMode) {
                    this.sensAnalysisItem = {};
                    this.editItemMode = false;
                }

            },
            createItem: function () {
                this.sensAnalysisItem.modelId = this.modelInfo.id;
                this.isLoading = true;
                this.$post("/riskAnalysis/item/create", this.sensAnalysisItem, (response) => {
                    this.$message({
                        message: '创建成功',
                        type: 'success'
                    });
                    this.itemDlgVisible = false;
                    this.loadItemList(this.modelInfo.id);
                },()=>{
                  this.isLoading = false;
                });
            },
            updateItem: function () {

              this.isLoading = true;
                this.$post("/riskAnalysis/item/update", this.sensAnalysisItem, (response) => {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.itemDlgVisible = false;
                    this.loadItemList(this.modelInfo.id);
                },()=>{
                  this.isLoading = false;
                });
            },
            deleteItem: function (id) {
              this.$confirm('该操作不可恢复, 是否继续?', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.isLoading = true;
                this.$post("/riskAnalysis/item/delete?id=" + id, {}, () => {
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                  this.loadItemList(this.modelInfo.id);
                },()=>{
                  this.isLoading = false;
                });
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '取消操作'
                });
              });
            },
            loadItemList: function (id) {
                this.loadingItem = true;
                this.$get("/riskAnalysis/item/data", {modelId: id}, (response) => {
                    this.itemList = response.data;
                }, () => {
                    this.loadingItem = false;
                });

            },

            openEditComputUnitDlg: function (data) {
                this.sensAnalysisItem = JSON.parse(JSON.stringify(data));
                var fieldIdList = [];
                for(var field of this.sensAnalysisItem.fieldList) {
                    fieldIdList.push(field.id);
                }
                this.sensAnalysisItem.fieldIdList = fieldIdList;
                // if (this.sensAnalysisItem.unit) {
                //     this.sensAnalysisItem.unitRef = this.sensAnalysisItem.unit.ref;
                // }
                this.editItemMode = true;
                this.itemDlgVisible = true;
            },
            parseUnitList2OptionList(dataList) {
                var dataMap = {};
                for (var i = 0; i < dataList.length; i++) {
                    var item = dataList[i];
                    // this.computeUnitMap[item.ref] = item;
                    var list = dataMap[item.tag];
                    if (!list) {
                        list = [];
                        dataMap[item.tag] = list;
                    }
                    list.push(item);
                }
                var resultList = [];
                for (var key in dataMap) {
                    var list = dataMap[key];
                    var item = {label: key, value: key, children: []};
                    for (var i = 0; i < list.length; i++) {
                        item.children.push({label: list[i].name, value: list[i].ref});
                    }
                    resultList.push(item);
                }
                return resultList;
            },
            loadComputeUnitList: function (id) {
                // this.isLoading = true;
                this.$get("/compute/data", {
                    modelId: id, type: 'field,input,expression,compute,summary'
                }, (response) => {

                    var computeList = [];
                    var normalList = [];
                    var normalList2 = [];
                    for (var item of response.data) {
                        if (item.type == 'compute') {
                            computeList.push(item);
                        } else {
                            normalList.push(item);
                            if (item.type != 'expression') {
                                normalList2.push(item);
                            }
                        }

                    }


                    this.computeUnitList = this.parseUnitList2OptionList(computeList);
                    this.normalUnitList = this.parseUnitList2OptionList(normalList);
                    this.irrOptionList = this.parseUnitList2OptionList(normalList2);

                });

            },

            updateConfig: function () {

              this.isLoading = true;
                this.riskAnalysisConfig.modelId = this.modelInfo.id;
                this.$post("/riskAnalysis/config/update", this.riskAnalysisConfig, (response) => {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.configDlgVisible = false;
                },()=>{
                  this.isLoading = false;
                });
            },
            loadConfig: function (modelId) {

                this.$get("/riskAnalysis/config/data", {modelId: modelId}, (response) => {
                    if (response.data) {
                        this.riskAnalysisConfig = response.data;
                    }
                });
            },
            showChangeRate: function (config) {
                if (!config.changeStep) {
                    return '请输入变化幅度和变化次数';
                }
                if (config.changeStep <= 0) {
                    return '变化幅度或次数不合法';
                }
                var result = '变化率: ';
                var count = 20 / config.changeStep;
                for (var i = count; i > 0; i--) {
                    result += -config.changeStep * i + '% ';
                }
                result += '0% ';
                for (var i = 0; i <= count; i++) {
                    result += ' ' + config.changeStep * i + '% ';
                }
                return result;
            },

            changeStep: function (currentValue, oldValue) {
                if (currentValue != 7.5) {
                    return;
                }
                if (oldValue && oldValue > currentValue) {
                    this.riskAnalysisConfig.changeStep = 5;
                } else {
                    this.riskAnalysisConfig.changeStep = 10;
                }

            }

        },

    }
</script>

